package com.ctyon.watchsdk.client;

import android.util.Log;

import com.ctyon.watchsdk.task.WatchTask;

import java.util.concurrent.TimeUnit;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import static com.ctyon.watchsdk.config.Config.NETTY_CLIENT_HOST;
import static com.ctyon.watchsdk.config.Config.NETTY_CLIENT_PORT;

/**
 * @author pancm
 * @Title: NettyClient
 * @Description: Netty客户端 心跳测试
 * @Version:1.0.0
 * @date 2017年10月8日
 */
public class Client {

    private static final String TAG = "NettyClient";

    private EventLoopGroup clientGroup = new NioEventLoopGroup();

    private Bootstrap clientBootstrap;
    private Channel clientChannel;
    private long reConnect;

    public void init(long heartBeat, long reConnect) {
        this.reConnect = reConnect;

        clientBootstrap = new Bootstrap();
        clientBootstrap
                .group(clientGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true) // 不延迟，直接发送
                .option(ChannelOption.SO_KEEPALIVE, true) // 保持长连接状态
                .handler(new ClientFilter(heartBeat));

        connect();
    }

    /**
     * Netty创建全部都是实现自AbstractBootstrap。 客户端的是Bootstrap，服务端的则是 ServerBootstrap。
     **/
    public void connect() {
        if (null != clientChannel && clientChannel.isActive()) {
            return;
        }

        try {
            ChannelFuture connect = clientBootstrap.connect(NETTY_CLIENT_HOST, NETTY_CLIENT_PORT);
            connect.addListener((ChannelFutureListener) future -> {
                if (future.isSuccess()) {
                    Log.d(TAG, "\n[ Netty Client 连接成功 >>>>>>> ]\n");
                    Log.d(TAG, "setClientChannel");
                    clientChannel = future.channel();
                    WatchTask.getInstance().setClientChannel(clientChannel);
                } else {
                    Log.d(TAG, "Netty Client 连接失败");
                    if (reConnect > 0){
                        future.channel().eventLoop().schedule(() -> {
                            Log.d(TAG, "客户端重连 ... ");
                            connect();
                        }, reConnect, TimeUnit.SECONDS);
                    }
                }
            }).sync();

        } catch (Exception e) {
            Log.e(TAG, "Netty 连接异常 ：" + e);
        } finally {
            Log.d(TAG, "shutdownGracefully");
//            clientGroup.shutdownGracefully();
        }
    }

}
